import Vue from 'vue'
import { fabric } from 'fabric'
import { saveData } from './operate'

export const state = Vue.observable({
  currentSelect: null,
  canvas: null,
  data: [], // 画布中的对象元素
  record: []
})

export const setCanvs = function (canvas) {
  state.canvas = canvas
  state.canvas.on('object:modified', (e) => {
    saveData()
  })
}

export const addText = function (text) {
  const textObj = new fabric.Text(text, {})
  textObj.on('selected', (e) => {
    state.currentSelect = e.target
  })
  // textObj.set({
  //   fill: 'red'
  // })
  console.log(textObj)
  state.canvas.add(textObj)
  state.data.push(textObj)
  saveData()
}

export const addImage = function (url) {
  fabric.Image.fromURL(url, function (oImg) {
    oImg.set({
      // width: 375
    })
    if (oImg.width > window.innerWidth) {
      oImg.scaleToWidth(window.innerWidth)
    }
    oImg.on('selected', (e) => {
      state.currentSelect = e.target
    })
    console.log(oImg)
    state.canvas.add(oImg)
    saveData()
  })
}

export const exportToImage = function () {
  const dataURL = state.canvas.toDataURL({
    width: state.canvas.width,
    height: state.canvas.height,
    left: 0,
    top: 0,
    format: 'png'
  })
  const link = document.createElement('a')
  link.download = 'canvas.png'
  link.href = dataURL
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  if (window.uni) {
    window.uni.postMessage({
      data: {
        action: 'upload'
      }
    })
  }
}
